package com.newway.back.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.back.entity.SysUserEntity;
import com.newway.back.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        SysUserEntity sysUserEntity = sysUserMapper.selectOne(queryWrapper);
        if(sysUserEntity == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //组装用户信息
        MyUserDetails myUserDetails = new MyUserDetails();
        myUserDetails.setSysUserEntity(sysUserEntity);
        //获取角色
        List<String> roles = sysUserMapper.getRolesById(sysUserEntity.getId());
        //获取权限
        List<String> perms = sysUserMapper.getPermsById(sysUserEntity.getId());
        myUserDetails.setPerms(perms);
        myUserDetails.setRoles(roles);
        return myUserDetails;
    }
}